package br.ufrn.dimap.ase.squid.plugin;

import java.util.ArrayList;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;


import br.ufrn.dimap.ase.squid.core.facade.SourceCodeAnalyser;
import br.ufrn.dimap.ase.squid.core.models.squidmodel.SquidModel;
import br.ufrn.dimap.ase.squid.core.models.util.SquidModelContent;

public class CodeAnalyserDynamicActivator extends CompoundContributionItem implements BundleActivator  {
	private static final String CODEANALYSER_ID = "br.ufrn.dimap.ase.squid.codeanalyser";
	private static BundleContext context;
	private IProject iproject = null;
	public ArrayList<ActionContributionItem> actionList = new ArrayList<ActionContributionItem>();
	
	public CodeAnalyserDynamicActivator(){
		makeActions();
	}

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		CodeAnalyserDynamicActivator.context = bundleContext;
		
	}

	public void stop(BundleContext bundleContext) throws Exception {
		
		CodeAnalyserDynamicActivator.context = null;
	}
	
	protected IContributionItem[] getContributionItems() {
		
		return actionList.toArray(new IContributionItem[actionList.size()]);
	}


	
	private void makeActions() {
		
		IConfigurationElement[] config = Platform.getExtensionRegistry()
				.getConfigurationElementsFor(CODEANALYSER_ID);
		System.out.println("Evaluating extensions");
		try {
			for (IConfigurationElement e : config) {				
				
				final Object o = e.createExecutableExtension("class");
				if (o instanceof SourceCodeAnalyser) {
					
					Action action = new Action() {
						public void run() {
							executeExtension(o);
						}
					};
					
					action.setText(((SourceCodeAnalyser) o).getName());
					action.setToolTipText(((SourceCodeAnalyser) o).getName());
					action.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
							.getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
					actionList.add(new ActionContributionItem(action));
					
				}
			}
		} catch (CoreException ex) {
			System.out.println(ex.getMessage());
		}
	}
	
	private void executeExtension(final Object o) {
		ISafeRunnable runnable = new ISafeRunnable() {
			@Override
			public void handleException(Throwable exception) {
				System.out.println("Exception in client");
			}

			@Override
			public void run() throws Exception {
				iproject = getProject();
				SourceCodeAnalyser codeAnalyser = ((SourceCodeAnalyser) o);
				SquidModel squidModel = codeAnalyser.runCodeAnalyser(iproject);
				SquidModelContent modelContent = new SquidModelContent(squidModel);
				modelContent.saveModel(codeAnalyser.getPath());
			}

		};
		SafeRunner.run(runnable);
	}

	private IProject getProject(){
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	    if (window != null)
	    {
	        IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection();
	        Object firstElement = selection.getFirstElement();
	        if (firstElement instanceof IAdaptable)
	        {
	            return (IProject)((IAdaptable)firstElement).getAdapter(IProject.class);
	        }
	    }
	    return null;
	}
	
//	private void showMessage(String message) {
//		MessageDialog.openInformation(null, "Sample View", message);
//	}
}
